﻿using System;
using System.Data.SqlClient;
using System.IO;
using Microsoft.WindowsAzure.Storage;
using Popw.LiveBlog.Config;

namespace Popw.LiveBlog.Repositories
{
	public interface IImageRepo
	{
		string BlobContainerName { get; }
		int SaveToDatabase(string fileName);
		void SaveToCdn(byte[] bytes, string fileName);
	}

	public class ImageRepo : IImageRepo
	{
		public string BlobContainerName
		{
			get { return Settings.BlobContainerName; }
		}

		public int SaveToDatabase(string fileName)
		{
			int id;
			using (var connection = new SqlConnection(ConnectionStrings.AzureDatabaseString))
			{
				var sql = String.Format("INSERT INTO Images (FileName) VALUES (@FileName);SELECT SCOPE_IDENTITY()");
				var command = new SqlCommand(sql, connection);
				command.Parameters.AddWithValue("@FileName", fileName);
				connection.Open();
				id = Convert.ToInt32(command.ExecuteScalar());
				connection.Close();
			}
			return id;
		}

		public void SaveToCdn(byte[] bytes, string fileName)
		{
			var storageAccount = CloudStorageAccount.Parse(ConnectionStrings.AzureStorageString);
			var client = storageAccount.CreateCloudBlobClient();
			var container = client.GetContainerReference(BlobContainerName);
			var blob = container.GetBlockBlobReference(fileName);
			blob.Properties.ContentType = "image/jpeg";
			using (var stream = new MemoryStream(bytes))
			{
				blob.UploadFromStream(stream);
			}
		}
	}
}